package com.wosiliujing.learning.config;

import com.wosiliujing.learning.component.Oauth2WebResponseExceptionTranslator;
import com.wosiliujing.learning.constant.SecurityConstants;
import com.wosiliujing.learning.service.MyClientDetailService;
import com.wosiliujing.learning.service.MyUserDetailServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;

/**
 * @author liujing
 * @date 2019/4/27 18:08
 */
@Configuration
@AllArgsConstructor
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final DataSource dataSource;

    private final AuthenticationManager authenticationManager;

    private final RedisConnectionFactory redisConnectionFactory;

    private final MyUserDetailServiceImpl myUserDetailService;

    /**
     * 配置redis存储
     * @return
     */
    @Bean
    public TokenStore tokenStore(){
        RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
        tokenStore.setPrefix(SecurityConstants.TOKEN_PREFIX);
        return tokenStore;
    }

    /**
     * /oauth/token支持client_id以及client_secret作登录认证
     * @param security
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security)  {
        security.allowFormAuthenticationForClients().checkTokenAccess("permitAll()");
    }

    /**
     * 配置数据库查询客户端
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        MyClientDetailService myClientDetailService = new MyClientDetailService(dataSource);
        myClientDetailService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
        myClientDetailService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
        clients.withClientDetails(myClientDetailService);
    }

    /**
     * 配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)
     * @param endpoints
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)  {
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.POST,HttpMethod.GET)
        .tokenStore(tokenStore())
        .userDetailsService(myUserDetailService)
        .authenticationManager(authenticationManager)
        .reuseRefreshTokens(false)
                .exceptionTranslator(new Oauth2WebResponseExceptionTranslator());

    }


}
